package com.yjymm.commonsdk.config.interceptor;

import com.yjymm.commonsdk.common.LoginUserContext;
import com.yjymm.commonsdk.common.exception.en.CommonResultEnum;
import com.yjymm.commonsdk.model.CommonResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author yjymm
 * @date 2021-01-13 23:14
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登录过滤器链，需在META/INF/services/com.yjymm.commonsdk.config.interceptor.LoginInterceptor文件中配置
     */
    private static List<LoginFilter> loginFilterList;

    static {
        Iterator<LoginFilter> iterator = ServiceLoader.load(LoginFilter.class).iterator();
        loginFilterList = new ArrayList<>();
        while (iterator.hasNext()) {
            loginFilterList.add(iterator.next());
        }
        loginFilterList.sort((x, y) -> {
            return x.getOrderNum() - y.getOrderNum();
        });

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        for (LoginFilter loginFilter : loginFilterList) {
            if (LoginUserContext.getUserInfo() != null) {
                // 验证成功
                return true;
            }
            if (!loginFilter.doVerify(request, response, handler)) {
                CommonResult build = CommonResult.builder()
                        .code(CommonResultEnum.NO_LOGIN.getCode())
                        .message(CommonResultEnum.NO_LOGIN.getMessage())
                        .build();
                response.getWriter().write(LoginUserContext.getObjectMapper().writeValueAsString(build));
            }
        }
        return false;
    }
}
